#define _CRT_SECURE_NO_WARNINGS 1
#include"Heap.h"
void HPInit(HP* php)
{
	assert(php);
	php->arr = NULL;
	php->capacity = php->size = 0;
}
void HPDestroy(HP* php)
{
	assert(php);
	if (php->arr)
		free(php->arr);
	php->arr = NULL;
	php->capacity = php->size = 0;
}
void Swap(int* x, int* y)
{
	int temp = *x;
	*x = *y;
	*y = temp;
}
void Adjustup(HPDatatype* arr, int child)
{
	int parent = (child - 1) / 2;
	while (child>0)
	{
		if (arr[parent] >arr[child])
		{
			Swap(&arr[parent], &arr[child]);
			child = parent;
			parent = (child - 1) / 2;
		}
		else
		{
			break;
		}
	}
}
void HPPush(HP* php, HPDatatype x)
{
	assert(php);
	if (php->size == php->capacity)
	{
		int newcapacity = php->capacity == 0 ? 4 : 2 * php->capacity;
		HPDatatype* temp = (HPDatatype*)realloc(php->arr, sizeof(HPDatatype) * newcapacity);
		if(temp==NULL)
		{
			perror("realloc fail!");
			exit(1);
		}
		php->arr = temp;
		php->capacity = newcapacity;
	}
	php->arr[php->size] = x;
	Adjustup(php->arr, php->size);
	php->size++;
}
bool HPEmpty(HP* php)
{
	assert(php);
	return php->size == 0;
}
void Adjustdown(HPDatatype* arr, int parent, int size)
{
	int child = 2 * parent + 1;
	while (child<size)
	{
		if (child+1<size && arr[child] > arr[child + 1])
		{
			child++;
		}
		if (arr[child] < arr[parent])
		{
			Swap(&arr[child], &arr[parent]);
			parent = child;
			child = parent * 2 + 1;
		}
		else
		{
			break;
		}
	}
}
void HPPop(HP* php)
{
	assert(php);
	assert(!HPEmpty(php));
	Swap(&php->arr[0], &php->arr[php->size - 1]);
	php->size--;
	Adjustdown(php->arr, 0, php->size);
}
HPDatatype HPTop(HP* php)
{
	assert(php && php->size);
	return php->arr[0];
}
int HPSize(HP* php)
{
	assert(php);
	return php->size;
}